<template>
    <el-dialog :model-value="modelValue" title="文件上传" width="30%" :close-on-press-escape="false" :close-on-click-modal="false"
               :show-close="false"
               :lock-scroll="false">
    <ul>
      <li v-for="(item,index) in queue" :key="index">
        <p>{{item.name}}</p>
          <el-progress :percentage="item.progress">
            <span>{{ item.message }}</span>
          </el-progress>
      </li>
    </ul>
    </el-dialog>
</template>

<script>
import { onBeforeMount, ref, toRefs } from 'vue'
import { get, postUploadProgress } from '@/utils/httpRequest'
import { Md5ExistUrl, uploadUrl } from '@/api/api'
import SparkMD5 from 'spark-md5'

export default {
  name: 'commonUpload',
  setup (props, { emit }) {
    const { files } = toRefs(props)
    // 最终返回给应用的文件列表
    const finalFiles = ref([])
    const upload = async (list, index) => {
      if (index + 1 <= list.length) {
        // 定义文件读取
        const fileReader = new FileReader()
        const sparkLocal = new SparkMD5.ArrayBuffer()
        let md5
        list[index].message = '正在计算文件md5，请稍候...'
        fileReader.readAsArrayBuffer(list[index].file)
        fileReader.onload = async (e) => {
          sparkLocal.append(e.target.result)
          md5 = sparkLocal.end()
          console.log(md5)
          const result0 = await get(Md5ExistUrl, { md5 })
          if (result0.code === 200) {
            // 当前文件已经存在
            if (result0.data) {
              finalFiles.value.push(result0.data)
              list[index].progress = 100
              list[index].message = '完成'
              await upload(list, index + 1)
            } else {
              // 当前文件不存在，开始上传
              const formData = new FormData()
              formData.append('file', list[index].file)
              formData.append('md5', md5)
              formData.append('generateUrl', false)
              const progress = (e) => {
                const complete = parseInt((e.loaded / e.total) * 100)
                list[index].progress = complete
                list[index].message = '正在传输数据到服务端'
                if (list[index].progress === 100) {
                  list[index].message = '正在等待服务端处理'
                }
                console.log('上传信息--', e)
              }
              const result1 = await postUploadProgress(uploadUrl, formData, progress)
              if (result1.code === 200) {
                finalFiles.value.push(result1.data)
                list[index].message = '完成'
                await upload(list, index + 1)
              } else {
                list[index].message = result1.message
              }
            }
          }
        }
      } else {
        console.error('finalFiles--', finalFiles.value)
        // 没有可用的文件进行上传了，马上通知应用
        emit('fileUploadFinished', finalFiles.value)
        emit('update:modelValue', false)
      }
    }
    // 上传队列
    const queue = ref([])
    onBeforeMount(() => {
      // 构造参数
      Array.from(files.value).forEach(item => {
        const tempFileItem = {}
        Object.assign(tempFileItem, item)
        tempFileItem.name = item.name
        tempFileItem.file = item
        tempFileItem.progress = 0
        tempFileItem.message = '等待上传'
        queue.value.push(tempFileItem)
      })
      // 开始上传
      upload(queue.value, 0)
    })
    return {
      queue
    }
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    // 待上传的文件列表
    files: {
      type: Array,
      required: true,
      default () {
        return []
      }
    }
  }
}
</script>

<style scoped>
</style>
